package com.logos.ruralrevitalization.utils;

import com.logos.ruralrevitalization.constant.RedisConstant;
import org.springframework.stereotype.Component;
import com.logos.ruralrevitalization.redis.RedisUtil;

import javax.annotation.Resource;
import java.security.SecureRandom;
import java.util.concurrent.TimeUnit;

@Component
public class CaptchaUtil {

    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    private static final int CAPTCHA_LENGTH = 5;
    private static final SecureRandom RANDOM = new SecureRandom();

    @Resource
    private RedisUtil redisUtil;

    /**
     * 生成一个五位验证码
     *
     * @return 五位验证码字符串
     */
    public String generateCaptcha() {
        StringBuilder captcha = new StringBuilder(CAPTCHA_LENGTH);
        for (int i = 0; i < CAPTCHA_LENGTH; i++) {
            int index = RANDOM.nextInt(CHARACTERS.length());
            captcha.append(CHARACTERS.charAt(index));
        }
        // 全部转为小写
        StringBuilder redisCaptcha = new StringBuilder();
        for (int i = 0; i < CAPTCHA_LENGTH; i++) {
            redisCaptcha.append(Character.toLowerCase(captcha.charAt(i)));
        }
        redisUtil.setNx(RedisConstant.CAPTCHA_CODE + redisCaptcha, redisCaptcha.toString(), 3L, TimeUnit.MINUTES);
        return captcha.toString();
    }
}
